package com.wz.jae.app.network


import android.content.Intent
import com.google.gson.Gson
import com.squareup.moshi.Moshi
import com.wz.common.base.appContext
import com.wz.jae.data.model.bean.ApiResponse

import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException

/**
 * 作者　:zwz
 * 时间　: 2022/9/29
 * 描述　: token过期拦截器
 */
class TokenOutInterceptor : Interceptor {

    //json数据转换工具
    private val moshi: Moshi = Moshi.Builder().build()
    @kotlin.jvm.Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val jsonAdapter = moshi.adapter(ApiResponse::class.java)
        val response = chain.proceed(chain.request())
        return if (response.body() != null && response.body()!!.contentType() != null) {
            val mediaType = response.body()!!.contentType()
            val string = response.body()!!.string()
            val responseBody = ResponseBody.create(mediaType, string)
            //
            val apiResponse = jsonAdapter.fromJson(string)
            //判断逻辑,token过期了需要什么操作
            if (apiResponse != null) {
                if (apiResponse.errorCode == 99999) {
                    //如果是普通的activity话 可以直接跳转，如果是navigation中的fragment，可以发送通知跳转
//                    appContext.startActivity(Intent(appContext, TestActivity::class.java).apply {
//                        flags = Intent.FLAG_ACTIVITY_NEW_TASK
//                    })
                }
            }



            response.newBuilder().body(responseBody).build()
        } else {
            response
        }
    }
}